package com.tueye.web.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.tueye.base.util.Page;
import com.tueye.entity.Adinfo;
import com.tueye.entity.Adsite;
import com.tueye.entity.user.User;

import com.tueye.service.IAdsiteService;
import com.tueye.service.usermanager.IRegisterService;

import com.tueye.utils.DateUtils;
import com.tueye.utils.TuEyeConstant;
import com.tueye.utils.UUIDGenerator;

/**
 * 用户添加控制层操作demo
 * spring mvc 2.5 支持MultiActionController
 * @author hanxiaowei
 *
 */
@SuppressWarnings("unchecked")
@org.springframework.stereotype.Controller
@RequestMapping("/usermanager.do")
public class UserController extends BaseController {
	private Log log = LogFactory.getLog(UserController.class);
	
	@Autowired
	@Qualifier("registerService")
	private IRegisterService registerService;
	
	//@RequestMapping(method = { RequestMethod.POST })
	@RequestMapping(params = "action=PageShow")
	public String PageShow (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// js传过来的参数列表：
		// page:页数
		// rp:每页显示多少条
		// sortname：排序的字段名称
		// sortorder: 排序的方向；比如：asc，desc；
		// query : 查询的条件
		// qtype ：查询的类型
		
		String rp=request.getParameter("rp"); //每页显示的数据数
		String pageString=request.getParameter("page");//获取 flexgrid传过来的页数。
		String query=request.getParameter("query");//获取 查询的条件
		if(null != query)
		query = java.net.URLDecoder.decode(query , "UTF-8");//解码
		String error = request.getParameter("ss");
		//error.indexOf("23");
		String qtype=request.getParameter("qtype");//获取 查询的类型
		String sortorder=request.getParameter("sortorder");//获取 查询的类型
		if(pageString == null || pageString.length() == 0) {
			pageString = "1";
		}
		StringBuffer hql = new StringBuffer(" from com.tueye.entity.user.User ");
		//if(StringUtils.isNotEmpty(query)) hql.append(" where "+query);
		if(StringUtils.isNotEmpty(query)) hql.append(" where "+qtype+" ='"+query+"'");
		if(StringUtils.isNotEmpty(qtype))hql.append("   order   by "+qtype);
		if(StringUtils.isNotEmpty(sortorder))hql.append("   "+sortorder);
		System.out.println("##########hql:"+hql.toString());
		Page pageModel = registerService.pagedQueryByHQL(hql.toString(), Integer.valueOf(pageString), Integer.valueOf(rp), null);
		
		Map pageInfo = new HashMap();
		pageInfo.put("page", new Integer(pageString));
		pageInfo.put("total", pageModel.getTotalCount());
		System.out.println("&&&&&&"+pageModel.getTotalCount());
		//生成json字符串
//		if(pageModel.getResult() instanceof ArrayList){
//			System.out.println("*******"+pageModel.getResult());
//			
//		}
		String jsonStr = getJsonString((ArrayList)pageModel.getResult(),pageInfo);
		log.info("###############:"+jsonStr);
		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(jsonStr);
		
/*		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.setHeader("Pragma", "no-cache");
		response.getWriter().write(jsonStr);
		response.getWriter().flush();
		response.getWriter().close();*/
		
		return null;
	}
	
	@RequestMapping(params = "action=delete")
	public String delete (HttpServletRequest request, HttpServletResponse response){
		
		String retult = "true";
		try {
			request.setCharacterEncoding("UTF-8");
			String id = request.getParameter("id");
			String mainId[]=id.split("\\,");
			for(int i=0;i <mainId.length;i++){ 
			
			//把id 弄成数组，for循环一一删掉
			User user =  registerService.getUserById(mainId[i]);
			String fn = user.getUserPoto();
		
			delFiles(fn);
			registerService.delUser(mainId[i]);
			//response.getWriter().print("true");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("#####出错了"+e.getMessage());
			
		}
		return null;
	}
	

	
	
	/**
	 * @param list
	 * @param pageInfo
	 * @return
	 */
	private String getJsonString(List list, Map pageInfo) {

		List mapList = new ArrayList();   
		for (int i = 0; i < list.size(); i++) {
			User user = (User) list.get(i);
			String id = user.getId();
			Map cellMap = new HashMap();
			cellMap.put("numid", i+1);
			cellMap.put("userinfos", "<a href=\"javascript:openWinrain("+id+")\";>查看</a>");
    		cellMap.put("cell", new Object[]{
    				
    				user.getId(),
    				i+1,
    				user.getByname(),
    				user.getEmail(),
    				user.getPassword(),
    				user.getHomeplace(),
    				user.getActiveArea(),
    				DateUtils.getDate2Str("yyyy-MM-dd HH:mm",user.getSys_time()),
    				"<a href=\"javascript:openWinrain('"+id+"')\";>查看</a>"
    				});
    		  
    				mapList.add(cellMap);
    				
		}
		
    	pageInfo.put("rows", mapList);
    	com.tueye.ajax.json.JSONObject object = new com.tueye.ajax.json.JSONObject(pageInfo);
    	return object.toString();
	}
	/**
	 * 
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("unused")
	private Object getJsonString(Object obj){
		
		JSONObject json = JSONObject.fromObject(obj);
		log.info("############# "+json);
		return json;
	}
	public boolean delFiles(String fn)  //fn为要删除的文件名，不包括路径 
	   { 
	   try 
	   { 
	   String newpath = TuEyeConstant.PROJECT_TOPIC_PATH +File.separatorChar+"usermanager/userphoto"+File.separatorChar; 
	   File file=new File(newpath+fn);  
	   System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"+newpath+fn); 
	   if(file.exists()) 
	  { 
	     file.delete(); 
	     System.out.println(file.getPath()+"delete file successfully!"); 
	 return true; 
	       }else 
	   { 
	 System.out.println("the file is not existed!"); 
	 return true; 
	    } 
	   }catch(Exception e) 
	   { 
	   System.out.println(e.toString()); 
	   return false; 
	   } 
	   } 

	
}
